$(function() {
    $("body").i18n();
    var devOrgs;
    $.ajax({
        url : contextPath + '/sample/loadDevOrgs.pvt',
        dataType : 'json',
        async : false,
        success : function(resp) {
            if (resp.success !== undefined && resp.success === false) {
                $.messager.alert($.i18n.get('error'), resp.msg || $.i18n.get("prompt.connection.exception"), 'error');
            } else {
                if ($.isArray(resp['devOrgs'])) {
                    devOrgs = resp['devOrgs'];
                }
            }
        }
    });
    if (devOrgs == undefined) {
        devOrgs = [];
    }
    $("#select_devOrgId").combobox({
        data : devOrgs,
        valueField : 'id',
        textField : 'name',
        panelHeight : 'auto',
        multiple : false,
        editable : false
    });

    $('#budgetGrid').datagrid({
        toolbar : '#datagrid-toolbar',
        url : contextPath + '/sample/findPageByBudget.pvt',
        pagination : true,
        pageSize : 10,
        rownumbers : true,
        striped : true,
        singleSelect : true,
        idField : 'id',
        nowrap : false,
        pagePosition : 'top',
        totalProperty : "total",
        rowsProperty : "budgets",
        frozenColumns : [[{
            field : 'id',
            checkbox : true
        }]],
        columns : [[{
            field : 'year',
            align : 'center',
            width : 160,
            title : $.i18n.get('budget.year'),
            sortable : true
        }, {
            field : 'money',
            align : 'center',
            width : 140,
            title : $.i18n.get('budget.money'),
            sortable : true
        }, {
            field : 'itemsCount',
            align : 'center',
            width : 160,
            title : $.i18n.get('budget.items.count')
        }]],
        onBeforeLoad : function(param) {
            if (!$("#queryForm").form('validate')) {
                return false;
            }
            $.extend(param, $('#queryForm').serializeJson());
            return true;
        }
    });
    window.onSearch = function() {
        $('#budgetGrid').datagrid('clearSelections').datagrid('load', {})
    }
    window.onAdd = function() {
        window.isEditing = false;
        $("#budgetDialog").dialog({
            title : $.i18n.get('add')
        }).dialog('open');
        onReset();
    }
    window.onEdit = function() {
        var selectedRow = getSelectedRow('#budgetGrid');
        if (selectedRow) {
            doEdit(selectedRow);
        }
    }
    function doEdit(selectedRow) {
        window.isEditing = true;
        window.editRow = selectedRow;
        $("#budgetDialog").dialog({
            title : $.i18n.get('edit')
        }).dialog('open');
        onReset();
    }
    window.onReset = function() {
        $('#budgetForm').form('reset');
        if (window.isEditing && window.editRow != undefined && window.editRow != null) {
            var formData = $.extend({}, window.editRow);
            $('#budgetForm').form('load', formData);
            $('#budgetItemsGrid').datagrid({
                data : formData.budgetItems
            });
        } else {
            $('#budgetForm').form('load', {
                year : null,
                money : null
            });
            $('#budgetItemsGrid').datagrid({
                data : []
            });
        }
    }
    
    window.onAddBudgetItem = function() {
        if (budgetItemEditing()) {
            $('#budgetItemsGrid').datagrid('insertRow', {
                row : {
                    id : null,
                    devOrgId : null,
                    flag : null,
                    money : null
                }
            });
        }
    }
    
    window.onAcceptBudgetItem = function(){
        budgetItemEditing();
    }
    
    window.onDelBudgetItem = function() {
        var selectedRows = $('#budgetItemsGrid').datagrid('getSelections');
        if (selectedRows.length > 0) {
            var idx = $('#budgetItemsGrid').datagrid('getRowIndex',selectedRows[0]);
            $('#budgetItemsGrid').datagrid('deleteRow', idx);
        } else {
            $.messager.alert($.i18n.get('prompt'), $.i18n.get('selectOneRecord'), 'info');
        }
    }
    
    $.extend($.fn.datagrid.methods, {
        editCell : function(jq, param) {
            return jq.each(function() {
                var opts = $(this).datagrid('options');
                var fields = $(this).datagrid('getColumnFields', true).concat($(this).datagrid('getColumnFields'));
                for (var i = 0; i < fields.length; i++) {
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    col.editor1 = col.editor;
                    if (fields[i] != param.field) {
                        col.editor = null;
                    }
                }
                $(this).datagrid('beginEdit', param.index);
                for (var i = 0; i < fields.length; i++) {
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    col.editor = col.editor1;
                }
            });
        }
    });
    
    var budgetItemEdit = {};
    function budgetItemEditing() {
        if (budgetItemEdit.editIndex == undefined) {
            return true
        }
        if ($('#budgetItemsGrid').datagrid('validateRow', budgetItemEdit.editIndex)) {
            $('#budgetItemsGrid').datagrid('endEdit', budgetItemEdit.editIndex);
            budgetItemEdit.editIndex = undefined;
            return true;
        } else {
            return false;
        }
    }
    
    $('#budgetItemsGrid').datagrid({
        toolbar : '#budgetItems-toolbar',
        pagination : false,
        rownumbers : true,
        singleSelect : true,
        idField : 'id',
        nowrap : false,
        pagePosition : 'top',
        totalProperty : "total",
        rowsProperty : "budgets",
        columns : [[{
            field : 'devOrgId',
            align : 'center',
            width : 180,
            title : $.i18n.get('budgetItem.devOrg'),
            editor : {
                type : 'combobox',
                options : {
                    data : devOrgs,
                    valueField : 'id',
                    textField : 'name',
                    panelHeight : 'auto',
                    multiple : false,
                    editable : false,
                    required : true
                }
            },
            formatter : function(value) {
                for (var i = 0; i < devOrgs.length; i++) {
                    if (devOrgs[i]['id'] == value) {
                        return devOrgs[i]['name'];
                    }
                }
            }
        }, {
            field : 'flag',
            align : 'center',
            width : 120,
            title : $.i18n.get('budgetItem.flag'),
            formatter : function(value) {
                if (value == 'true' || value == true) {
                    return "<span class='icon-grid-cell icon-ok'></span>";
                }
                return "<span class='icon-grid-cell icon-cancel'></span>";
            },
            editor : {
                type : 'checkbox',
                options : {
                    on : 'true',
                    off : 'false'
                }
            }
        }, {
            field : 'money',
            align : 'center',
            width : 150,
            title : $.i18n.get('budgetItem.money'),
            editor : {
                type : 'numberbox',
                options : {
                    precision : 2,
                    min : 0,
                    required : true
                }
            }
        }]],
        onClickCell : function(index, field) {
            if (budgetItemEditing()) {
                $('#budgetItemsGrid').datagrid('selectRow', index).datagrid('editCell', {
                    index : index,
                    field : field
                });
                budgetItemEdit.editIndex = index;
            }
        }
    });
    
    function getSelectedRow(selector, multiple) {
        var selectedRows = $(selector).datagrid('getSelections');
        if (selectedRows.length == 0) {
            showPromptMsg($.i18n.get('selectMinOneRecord'));
            return false;
        } else if (!multiple && selectedRows.length > 1) {
            showPromptMsg($.i18n.get('selectOneRecord'));
            return false;
        } else {
            return multiple ? selectedRows : selectedRows[0];
        }
    }
    function showPromptMsg(msg) {
        $.messager.alert($.i18n.get('prompt'), msg, 'warning');
    }
    
    window.onSave = function() {
        if (!budgetItemEditing()) {
            return false;
        }
        if (!$("#budgetForm").form("validate")) {
            $.messager.alert($.i18n.get('error'), $.i18n.get('validateError'), 'error');
            return false;
        }
        var items = $('#budgetItemsGrid').datagrid('getRows');
        if (items.length == 0) {
            $.messager.alert($.i18n.get('error'), $.i18n.get('validateError'), 'error');
            return false;
        }
        for (var idx = 0; idx < items.length; idx++) {
            var devOrgId = items[idx].devOrgId;
            var money = items[idx].money;
            if (null == devOrgId || null == money) {
                $.messager.alert($.i18n.get('error'), $.i18n.get('validateError'), 'error');
                return false;
            }
        }
        var budget = $("#budgetForm").serializeJson();
        if (window.isEditing) {
            budget.id = window.editRow.id;
        }
        budget.budgetItems = [];
        for (var idx = 0; idx < items.length; idx++) {
            budget.budgetItems.push({
                id : items[idx].id,
                devOrgId : items[idx].devOrgId,
                flag : ('true' == items[idx].flag || items[idx].flag === true),
                money : items[idx].money
            });
        }
        $.ajax({
            type : 'post',
            url : contextPath + "/sample/saveBudget.pvt",
            data : JSON.stringify({budget : budget}),
            contentType : 'application/json; charset=UTF-8',
            processData : false,
            dataType : 'json',
            success : function(resp, status, xhr) {
                $.messager.progress('close');
                if (resp.success) {
                    $("#budgetDialog").dialog('close');
                    $.messager.alert($.i18n.get('prompt'), $.i18n.get('saveSuccess'), 'info', function(){
                        onSearch();
                    });
                } else {
                    $.messager.alert($.i18n.get('error'), resp.msg || $.i18n.get("prompt.exception"), 'error');
                }
            },
            error : function(xhr, status, error) {
                $.messager.progress('close');
                $.messager.alert($.i18n.get('error'), error || $.i18n.get("prompt.connection.exception"), 'error');
            }
        });
    }
    
    window.onDel = function() {
        var selectedRow = getSelectedRow('#budgetGrid', true);
        if (selectedRow) {
            $.messager.confirm($.i18n.get('prompt'), $.i18n.get('confirmDeleteData'), function(result) {
                if (result) {
                    var ids = [];
                    $(selectedRow).each(function() {
                        ids.push(this.id);
                    });
                    $.messager.progress({
                        title : $.i18n.get('prompt'),
                        msg : $.i18n.get('waitingMessage')
                    });
                    $.ajax({
                        url : contextPath + '/sample/deleteBudgets.pvt',
                        data : {
                            ids : ids.join(",")
                        },
                        type : "post",
                        success : function(resp) {
                            $.messager.progress('close');
                            if (resp.success == true) {
                                onSearch();
                            } else {
                                $.messager.alert($.i18n.get('error'), resp.msg, 'error');
                            }
                        },
                        error : function(xhr, status, error) {
                            $.messager.progress('close');
                            $.messager.alert($.i18n.get('error'), error || $.i18n.get("prompt.connection.exception"), 'error');
                        }
                    });
                }
            });
        }
    }
});